package com.demo.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.demo.service.ShortUrlService;
import com.demo.util.Base62Utils;
import com.demo.util.id.TableIdFactory;

@RequestMapping("/short")
@RestController
public class ShortUrlController {
	
	private final String SHORT_URL_PREFIX = "http://t.cn/" ;
	
	@Autowired
	private TableIdFactory tableIdFactory ;
	
	@Autowired
	private ShortUrlService shortUrlService ;
	
	@PostMapping("create")
	public String createShortUrl(@RequestBody JSONObject jsonParam) {
		// 简单模拟一下参数必输校验
		String oldUrl = jsonParam.getString("url") ;
		if(StringUtils.isEmpty(oldUrl)) {
			return "Error: url is null!" ;
		}
		// 1. 生成10进制序号
		String shortNum = this.tableIdFactory.generate() ;
		// 2. 将序号转换成6位的62进制数
		String shortKey = Base62Utils.base62Encode(Long.valueOf(shortNum)) ;
		// 3. 将短链接标识和原URL入库
		Map param = new HashMap() ;
		param.put("ShortId", shortKey) ;
		param.put("ShortOldUrl", oldUrl) ;
		this.shortUrlService.addShortUrl(param);
		// 4. 返回短链接地址给调用方
		return this.SHORT_URL_PREFIX + shortKey ;
	}
	
	@PostMapping("query")
	public String queryLongUrl(@RequestBody JSONObject jsonParam) {
		String shortKey = jsonParam.getString("shortKey") ;
		if(StringUtils.isEmpty(shortKey)) {
			return "Error: shortKey is null!" ;
		}
		return this.shortUrlService.queryLongUrl(shortKey) ;
	}

}
